package com.sysu.simulation.widget;


import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sysu.simulation.BaseFragment;
import com.sysu.simulation.R;
import com.sysu.simulation.adapter.BaseRecyclerAdapter;
import com.sysu.simulation.bean.ListResult;
import com.sysu.simulation.helper.CacheHelper;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public abstract class BaseRecyclerFragment<T> extends BaseFragment implements BaseRecyclerAdapter.OnItemClickListener,
        BaseRecyclerAdapter.OnItemLongClickListener,
        RecyclerSwipeRefreshLayout.RefreshLoadListener{

    protected RecyclerSwipeRefreshLayout mRefreshLayout;
    protected RecyclerView mRecyclerView;
    protected BaseRecyclerAdapter<T> mAdapter;
    protected TextHttpResponseHandler mHandler;
    private boolean hasCache = false;
    protected ListResult<T> mDatas;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recycler_base;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mRefreshLayout = (RecyclerSwipeRefreshLayout) root.findViewById(R.id.refreshLayout);
        mRecyclerView = (RecyclerView) root.findViewById(R.id.recyclerView);

        mAdapter = getAdapter();
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemLongClickListener(this);

        mRecyclerView.setLayoutManager(getLayoutManager());
        mRecyclerView.setAdapter(mAdapter);
        mRefreshLayout.setRefreshLoadListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        mDatas = new ListResult<>();
        mHandler = new TextHttpResponseHandler() {

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    ListResult<T> results = new Gson().fromJson(responseString, getResultType());
                    if (results != null && results.getItems() != null) {
                        setAdapterData(results);
                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(statusCode, headers, responseString, e);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                onComplete();
            }

            @Override
            public void onCancel() {
                super.onCancel();
                onComplete();
            }
        };

        if(hasCache) {
            List<T> items = CacheHelper.load(mContext, getCacheType(), getCacheKeyName());
            if(items == null) {
                mDatas.setItems(new ArrayList<T>());
            }
            else {
                mDatas.setItems(items);
                mAdapter.addItems(mDatas.getItems());
            }
            mRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mRefreshLayout.setRefreshing(true);
                    refresh();
                }
            });
        }

    }

    private void setAdapterData(ListResult<T> results) {
        mDatas.setNextItem(results.getNextItem());
        if(mRefreshLayout.isRefreshing()) {
            mDatas.setItems(results.getItems());
            mAdapter.clear();
            mAdapter.addItems(mDatas.getItems());
            if(hasCache) {
                CacheHelper.save(mContext, mDatas.getItems(), getCacheKeyName());
            }
        }
        else {
            mAdapter.addItems(results.getItems());
        }
    }

    @Override
    public void refresh() {
        mDatas.setNextItem(0);
        requestData();
    }

    @Override
    public void load() {
        requestData();
    }

    protected void requestData() {};

    protected abstract Type getResultType();

    protected abstract Type getCacheType();

    protected abstract String getCacheKeyName();

    protected void onComplete() {
        mRefreshLayout.complete();
    }

    protected void setCache(boolean needCache) {
        hasCache = needCache;
    }

    @Override
    public void onItemClick(int position, long itemId) {
        T item = mAdapter.getItem(position);
        if (item != null)
            onItemClick(item, position);
    }

    protected abstract void onItemClick(T item, int position);

    @Override
    public void onItemLongClick(int position, long itemId) {
        T item = mAdapter.getItem(position);
        if (item != null)
            onItemLongClick(item, position);
    }

    protected abstract void onItemLongClick(T item, int position);

    protected abstract BaseRecyclerAdapter<T> getAdapter();

    protected abstract RecyclerView.LayoutManager getLayoutManager();
}
